//
//  BIDExchangeDetailViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/13.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDExchangeDetailViewController.h"
#import "BIDExchangeDetailHeaderView.h"
#import "BIDExchangeDetailSectionHeaderView.h"
#import "BIDCustomTextView.h"
#import "BIDLeaveMsgCell.h"
#import "BIDShowImgCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

//详情
static NSString *detailURL = @"displaceAndroid/getById.action";
//留言列表
static NSString *leaveMsgListURL = @"displaceMessageAndroid/list.action";
//留言
static NSString *leaveMsgURL = @"displaceMessageAndroid/add.action";

@interface BIDExchangeDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UITextViewDelegate>
{
    NSArray *_imgArr;
    NSArray *_leaveMsgArr;
    BIDLeaveMsgCell *_tempLeaveMsgCell;
    BIDExchangeDetailHeaderView *_headerView;
    BOOL _isRegister;
}
@end

@implementation BIDExchangeDetailViewController
@synthesize exchangeID;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"宝贝详情";
    //
    _messageTextView.clipsToBounds = YES;
    _messageTextView.layer.cornerRadius = 4.f;
    _messageTextView.placeholder = @"留言";
    _messageTextView.delegate = self;
    //
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.allowsSelection = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _imgArr = [[NSArray alloc] init];
    _leaveMsgArr = [[NSArray alloc] init];
    //
    _tempLeaveMsgCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDLeaveMsgCell" owner:self options:nil] lastObject];
    //
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    [_tableView addGestureRecognizer:tapGR];
    //
    [self getDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 获取详情
 */
- (void)getDetail
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], detailURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"displace.id=%@", exchangeID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDExchangeDetailHeaderView" owner:self options:nil] lastObject];
            [_headerView adjustLayoutWithDic:responseDic];
            _tableView.tableHeaderView = _headerView;
            //
            NSArray *arr = responseDic[@"fileList"];
            if(arr.count > 0)
            {
                _imgArr = [[NSArray alloc] initWithArray:arr];
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
                //[_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                [_tableView reloadData];
            }
            //
            [self getLeaveMessageList];
        }
    }];
}

/**
 获取留言列表
 */
- (void)getLeaveMessageList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], leaveMsgListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.displaceId=%@", exchangeID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"rows"];
            _leaveMsgArr = [[NSArray alloc] initWithArray:arr];
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
            [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
}

/**
 留言
 */
- (void)toReply
{
    NSString *strMsg = _messageTextView.text;
    if(strMsg.length == 0)
    {
        [self showAlertView:@"请填写留言内容" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    else
    {
    }
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], leaveMsgURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&displaceMessage.displaceId=%@&displaceMessage.content=%@", [AppDelegate getUserId], self.exchangeID, strMsg];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _messageTextView.text = @"";
            [_messageTextView resignFirstResponder];
            [self getLeaveMessageList];
        }
    }];
}

- (void)tapGestureHandler:(UITapGestureRecognizer *)tapGR
{
    [_messageTextView resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.25f];
    _bottomForMessageViewConstraint.constant = self.keyboardHeight;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.30f];
    _bottomForMessageViewConstraint.constant = 0;
    [UIView commitAnimations];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat height = textView.contentSize.height;
    if(height >= 89)
    {
        _heightForMessageViewConstraint.constant = 89;
    }
    else
    {
        _heightForMessageViewConstraint.constant = height+10>40 ? height+10 : 40;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        [self toReply];
        return NO;
    }
    else
    {
        return YES;
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return _imgArr.count;
    }
    else
    {
        return _leaveMsgArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *showImgIdentifier = @"showImg";
    static NSString *leaveMsgIdentifier = @"leaveMsg";
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib1 = [UINib nibWithNibName:@"BIDShowImgCell" bundle:nil];
        [tableView registerNib:nib1 forCellReuseIdentifier:showImgIdentifier];
        UINib *nib2 = [UINib nibWithNibName:@"BIDLeaveMsgCell" bundle:nil];
        [tableView registerNib:nib2 forCellReuseIdentifier:leaveMsgIdentifier];
    }
    if(section == 0)
    {
        BIDShowImgCell *showImgCell = [tableView dequeueReusableCellWithIdentifier:showImgIdentifier];
        NSDictionary *dic = _imgArr[row];
        NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"path"]];
        [showImgCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"slide_placeholder.png"]];
        cell = showImgCell;
    }
    else
    {
        BIDLeaveMsgCell *leaveMsgCell = [tableView dequeueReusableCellWithIdentifier:leaveMsgIdentifier];
        NSDictionary *dic = _leaveMsgArr[row];
        NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"photo"]];
        [leaveMsgCell.avatarImgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"defaultPortrait.png"]];
        leaveMsgCell.nickLabel.text = dic[@"nickName"];
        leaveMsgCell.contentLabel.text = dic[@"content"];
        NSString *strTime = dic[@"createTime"];
        NSDate *date = [BIDGlobalMethods transToNSDateByFormatter:@"yyyy-MM-dd HH-mm-ss" fromStringDate:strTime];
        leaveMsgCell.timeLabel.text = [date timeIntervalDescription];
        cell = leaveMsgCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0.f;
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(section == 0)
    {
        height = 236*CGRectGetWidth(tableView.frame)/320;
    }
    else
    {
        _tempLeaveMsgCell.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(_tempLeaveMsgCell.contentLabel.frame);
        _tempLeaveMsgCell.contentLabel.text = _leaveMsgArr[row][@"content"];
        CGSize size = [_tempLeaveMsgCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        height = size.height>80 ? size.height+1 : 80;
    }
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return nil;
    }
    else
    {
        BIDExchangeDetailSectionHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDExchangeDetailSectionHeaderView" owner:self options:nil] lastObject];
        CGRect frame = headerView.frame;
        frame.size.width = CGRectGetWidth(headerView.frame);
        headerView.frame = frame;
        if(_leaveMsgArr.count > 0)
        {
            headerView.leaveMsgCount = _leaveMsgArr.count;
        }
        return headerView;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 25.f)];
    [view setBackgroundColor:[UIColor whiteColor]];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 0.f;
    else
    {
        return 56.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 25.f;
}
@end
